package com.kuisama.oss.autoconfigure;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.kuisama.oss.condiotion.AliyunOssCondition;
import com.kuisama.oss.properties.AliyunOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * aliyun oss 自动配置
 *
 * @author kuisama
 */
@Configuration
@EnableConfigurationProperties(AliyunOssProperties.class)
@Conditional(AliyunOssCondition.class)
@ConditionalOnProperty(prefix = "aliyun.oss", value = "true", matchIfMissing = true)
public class AliyunOssAutoConfiguration {
    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    /**
     * create OSS client
     */
    @Bean
    public OSSClient ossClient() {
        ClientConfiguration config = aliyunOssProperties.getClientConfig();
        String endpoint = aliyunOssProperties.getEndpoint();
        String accessKeyId = aliyunOssProperties.getAccessKeyId();
        String accessKeySecret = aliyunOssProperties.getAccessKeySecret();
        DefaultCredentialProvider defaultCredentialProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        if (config == null) {
            config = new ClientConfiguration();
        }
        return new OSSClient(endpoint, defaultCredentialProvider, config);
    }

}
